package edu.stthomas.seis770.visitor;

import COM.hilbertinc.xml.AbstractReflectiveVisitor;
import COM.hilbertinc.xml.HDOMUtil;
import org.w3c.dom.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * Visitor implementation for Exercise part 3 which uses reflection to dynamically decide which visit method to call
 * based on passed in visited object
 */
public class ReflectiveHTMLVisitor extends AbstractReflectiveVisitor {
    private Writer writer = null;

    private Writer getWriter() {
        if (writer == null) {
            writer = new PrintWriter(System.out);
        }
        return writer;
    }


    private void write(String string) throws IOException {
        getWriter().write(string);
    }

    public void flush() throws IOException {
        getWriter().flush();
    }


    public void visitDocument(Document document) throws IOException {
        write("<html>\n");
        write("<body>\n");
        if (document.hasChildNodes()) {
            NodeList children = document.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                dispatch(child);
            }
        }
        write("</body>\n");
        write("</html>\n");


    }

    public void visitDocumentType(DocumentType documentType) throws IOException {
        write("<h1> !DOCTYPE " + documentType.getName() + " SYSTEM ...</h1>\n");
    }

    public void visitElement(Element element) throws IOException {
        write("<h3>" + element.getTagName() + "</h3>\n");

        if (element.hasChildNodes()) {
            NodeList children = element.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                dispatch(child);
            }
        }
        write("<h3>" + element.getNodeName() + "</h3>\n");
    }

    public void visitText(Text text) throws IOException {
        String textString = HDOMUtil.trim(text);
        if (textString.equals("") || textString.equals("\\n")) {
            return;
        }
        write("<h2>" + textString + "</h2>\n");

    }

    @Override
    public void visit(Object object) {
        System.out.println("default visit method is called something is wrong");
    }


}
